<template>
  <div style="height: calc(100% - 44px)">
    <ul class="accordion">
      <!-- <li  v-if="type == 'tel'" v-for="(item,index) in tree" :key="index">
        <div v-if="item.leaf" @click="openUsual(item)">
          <div class="link">{{item.serde?item.serde:'不详'}}
          </div>
        </div>
        <div v-else>
          <div class="link" @click="openAccordion(item)"><i :class="'fa fa-chevron-down '+(item.open?'openImg':'')"></i>{{item[name]}}</div>
          <div :class="'submenu '+(item.open?'openChild':'')">
            <tree-root v-if="item[children]" :list="item[children]" :value="checked" :checkbox="checkbox" :name="name"
              :children="children" :loadData="loadData" :type="type" :users="users" :multiple="multiple"></tree-root>
          </div>
        </div>
      </li> -->
      <!-- 选人页面 -->
      <li v-for="(item,index) in tree" :key="index" v-if="type == 'dept'" style="width: 100%;">
        <!-- 人员信息（getPerson方法中，会给人员信息的leaf属性赋值为true） -->
        <div v-if="item.leaf" @click="openPerson(item)" style="width: 100%;overflow-x: hidden;">
          <div class="link" @click="check(item)"
            style="display: flex;align-items: center;width: 100%;overflow-x: hidden">
            <!-- todo -->
            <check-icon type="plain" :value="checked.includes(item[field])" style="float:left;margin-right: 9px"
              v-if="checkbox"></check-icon>
            <img style="height:14px; width:14px;margin-right: 12px" src="@/assets/img/person.png" />
            {{item[field]?item[field]:'不详'}}
            <!-- <div v-else-if="item.state" style="float:right"><i class="fa fa-circle" :style="'right:50px;left:auto;font-size:10px;margin-top:-6px;'+ setState(item.state)" ></i>{{item.state}}</div> -->
          </div>
        </div>
        <!-- 部门信息 -->
        <div v-else style="width: 100%;overflow-x: hidden">
          <div class="link" @click="openAccordion(item)" style="width: 100%;overflow-x: hidden">
            <img src="@/assets/img/层级.png" v-if="item.ORG_PATHID.split('.').length > 5" style="margin-right: 10px" />
            <img src="@/assets/img/树状图.png" v-else style="margin-right: 10px">
            <i :class="'fa fa-chevron-down '+(item.open?'openImg':'')"></i>{{item[name]}}</div>
          <div :class="'submenu '+(item.open?'openChild':'')" style="width: 100%;overflow-x: hidden">
            <tree-root v-if="item[children]" :list="item[children]" :value="checked" :checkbox="checkbox" :name="name"
              :usernames="checkedUserNames" :children="children" :loadData="loadData" :type="type" :users="users"
              :multiple="multiple" style="width: 100%;overflow-x: hidden" :prjId='prjId' @selectUser='selectUser'>
            </tree-root>
          </div>
        </div>
      </li>
      <!--<li v-if="type == 'person'" v-for="(item,index) in tree" :key="index">-->
      <li v-for="(item,index) in tree" :key="index" v-if="type == 'person'"
        style="width: 100%;overflow-x: hidden;margin-top: 0" class="search-person">
        <group style="width: 100%">
          <cell is-link :border-intent="false" :arrow-direction="item.showContent ? 'down' : 'right'"
            @click.native="item.showContent = !item.showContent">
            <img slot="title" src="../../assets/img/树状图.png" alt="" style="margin-right: 13px">
            <span slot="title">{{item.FIRSTDEPTNAME}}</span>
          </cell>

          <div class="slide" :class="item.showContent?'animate':''" style="padding-right: 0;">
            <group>
              <cell is-link :border-intent="false" :arrow-direction="item.showContent1 ? 'down' : 'right'"
                @click.native="item.showContent1 = !item.showContent1">
                <img slot="title" src="../../assets/img/层级.png" alt="" style="margin-right: 13px">
                <span slot="title">{{item.SECONDDEPTNAME}}</span>
              </cell>

              <div class="slide" :class="item.showContent1?'animate':''" style="padding-right: 0;">
                <group>
                  <cell is-link :border-intent="false" :arrow-direction="item.showContent2 ? 'down' : 'right'"
                    @click.native="item.showContent2 = !item.showContent2">
                    <img slot="title" src="../../assets/img/层级.png" alt="" style="margin-right: 13px">
                    <span slot="title">{{item.THIRDDEPTNAME}}</span>
                  </cell>
                  <div @click="openPerson(item)" style="width: 100%;overflow-x: hidden" class="slide"
                    :class="item.showContent2?'animate':''">
                    <div class="link" @click="check(item)"
                      style="display: flex;align-items: center;width: 100%;overflow-x: hidden">
                      <!-- todo -->
                      <check-icon type="plain" :value="checked.includes(item[field])"
                        style="float:left;margin-right: 9px" v-if="checkbox"></check-icon>
                      <img style="height:14px; width:14px;margin-right: 12px" src="@/assets/img/person.png" />
                      {{item[field]?item[field]:'不详'}}
                    </div>
                  </div>
                </group>
              </div>
            </group>
          </div>

        </group>
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: "treeRoot",
    props: {
      prjId: {
        type: String,
        default () {
          return '0'
        }
      },
      //部门-人员数据
      list: {
        type: Array,
        default () {
          return []
        }
      },
      //已选列表
      value: {
        type: Array,
        default () {
          return []
        }
      },
      //保存选择的对象
      users: {
        type: Array,
        default () {
          return []
        }
      },
      checkbox: {
        type: Boolean,
        default () {
          return false
        }
      },
      children: {
        type: String,
        default: 'children'
      },
      name: {
        type: String,
        default: 'name'
      },
      loadData: {
        type: Boolean,
        default () {
          return false
        }
      },
      type: {
        type: String,
        default () {
          return 'dept'
        }
      },
      multiple: {
        type: Boolean,
        default () {
          return false
        }
      },
      usernames: {
        type: Array,
        default () {
          return []
        }
      }
    },
    data() {
      return {
        checked: this.value,
        tree: JSON.parse(JSON.stringify(this.list)),
        checkedUserNames: this.usernames,
        flag: false
      }
    },
    methods: {
      selectUser(val) {
        this.$emit('selectUser', val)
      },
      openAccordion(item) {
        this.flag = true;
        this.$emit('flag', this.flag)
        if (this.loadData && !item.open) {
          if (item[this.children] && item[this.children].length > 0) {
            // this.$store.dispatch('getDept', {
            //   id: item.id,
            //   callback: (data) => {
            //     this.$set(item, this.children, data)
            //   }
            // })
          } else if ((!item.children || item.children == 0) && item.ORG_PATHID.split('.').length >
            3) { //TODO 部门长度>3是否需要
            this.getPerson(item);
          }
        }
        this.$nextTick(() => {
          this.$set(item, 'open', !item.open)
        })
      },
      //勾选
      check(val) {
        this.flag = true;
        this.$emit('flag', this.flag)
        // console.log(this.multiple)
        // console.log("checkedbefore",this.checked)
        // console.log("usernamebefore",this.checkedUserNames)
        if (this.multiple) {
          if (!this.checked.includes(val.USER_FULLNAME)) {
            this.users.push(val)
            this.checked.push(val.USER_FULLNAME)
            this.checkedUserNames.push(val.USER_NAME)
          } else {
            this.users.splice(this.users.findIndex(item => item === val), 1)
            this.checked.splice(this.checked.findIndex(item => item === val.USER_FULLNAME), 1)
            this.checkedUserNames.splice(this.checkedUserNames.findIndex(item => item === val.USER_NAME), 1)
          }
          // console.log("checkUsername",this.checkedUserNames)
          var testUserName = this.checkedUserNames.join(",")
          var userNames = this.getValues("USER_NAME")
          this.$emit('selectUser', testUserName);
          window.localStorage.setItem("handleName", userNames)
        } else {
          if (!this.checked.includes(val.USER_FULLNAME)) {
            this.users.splice(0, 1, val)
            this.checked.splice(0, 1, val.USER_FULLNAME)
          } else {
            this.users.splice(this.users.findIndex(item => item === val), 1)
            this.checked.splice(this.checked.findIndex(item => item === val.USER_FULLNAME), 1)
          }
          window.localStorage.setItem("handleName", val.USER_NAME)
          this.$emit('selectUser', val.USER_NAME)
        }
        // console.log(this.checked)
        this.$emit('input', this.checked)
      },
      getPerson(item) {
        this.flag = true;
        this.$emit('flag', this.flag)
        if (this.checkNetWork()) {
          console.log(item)
          console.log(
            '______________________________________------------------------------------________________________________'
          )
          // let params = "ac=data&action=contact&type=list&listtype=sublist&id=" +item.ORG_PATHID.replace(/^./,'').replace(/.$/,'')
          // if(this.checkbox) {
          //   params = "ac=data&action=chooseuser&type=list&listtype=sublist&id=" +item.ORG_PATHID;
          // }
          this.$ajax({
            method: 'post',
            url: this.COMMON_URL, //+ '?_method=V_USER_SELECT*getHRUserList&filter=&type=prj&projectId=0',
            data: {
              "_method": "V_USER_SELECT*getHRUserList",
              "type": "prj",
              "projectId": '0',
              // "MiniQueryFormData": '{"RoleId":"","GroupId":"'+item.ID+'","UserFullName":""}',
              //   "MiniQueryFormData": '{"RoleId":"","ChooseProjectId":"","GroupId":"","UserFullName":""}',
              "MiniQueryFormData": '{"RoleId":"","ChooseProjectId":"' + this.prjId + '","GroupId":"' + item.ID +
                '","UserFullName":""}', //by 江培   查询加上部门信息
              "pageIndex": "0",
              "pageSize": "1000",
              "sortField": "USER_FULLNAME",
              "sortOrder": "asc"
            }
          }).then((res) => {
            if (res.data && res.data && res.data.data) {
              this.$set(item, this.children, res.data.data.map(obj => {
                obj.leaf = true;
                return obj
              }))
            }
          })
        } else {
          //执行离线状态时的任务   
          this.$store.state.SQLiteDB.transaction((tx) => {
            tx.executeSql('SELECT * FROM USERSELECTINFO WHERE PRJID = "' + this.prjId +
              '" AND ORG_PATHID LIKE "%.' + item.ID + '.%"', [], (tx, result) => {
                if (result.rows) {
                  var temp = []
                  for (var i = 0; i < result.rows.length; i++) {
                    temp[i] = result.rows.item(i)
                  }
                  this.$set(item, this.children, temp.map(obj => {
                    obj.leaf = true;
                    return obj
                  }))
                }
              });
          }, (err) => {
            console.log('错误', err)
          })

        }

      },
      openPerson(item) {
        if (!this.checkbox) {
          this.$store.commit("SET_CURRENT_ROW", item)
          // this.$router.push('/index/addressBook/person', )
          this.$router.push({
            name: 'person',
            params: {
              item: item
            }
          })
        }
      },
      // openUsual(item) {debugger
      //   if (!this.checkbox) {
      //     this.$store.commit("SET_CURRENT_ROW",item)
      //     this.$router.push('/addressBook/usualInfo')
      //   }
      // },
      setState(val) {
        let cls = '#3c81f6'
        if (val == "在岗")
          cls = "#3c81f6";
        else if (val == "请假")
          cls = "yellow";
        else if (val == "出差")
          cls = "green";
        return 'color:' + cls
      },
      getValues(val) {
        return this.users.map(item => {
          return item[val]
        }).join(',')
      }
    },
    computed: {
      field() {
        return this.checkbox ? 'USER_FULLNAME' : 'USER_FULLNAME'
      },
    },
    watch: {
      value() {
        this.checked = this.value
      },
      list() {
        this.tree = JSON.parse(JSON.stringify(this.list))
      },
      usernames() {
        this.checkedUserNames = this.usernames
      }
    }
  }

</script>

<style scoped>
  .accordion {
    height: 97%;
    width: 100%;
    margin: 0 auto;
    background: #fff;
    overflow-y: auto;
  }

  .accordion .link {
    display: block;
    padding: 15px 15px 15px 42px;
    font-size: 14px;
    position: relative;
    -webkit-transition: all 0.4s ease;
    -o-transition: all 0.4s ease;
    transition: all 0.4s ease;
  }

  .link:before {
    content: " ";
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    border-top: 1px solid #d9d9d9;
    color: #d9d9d9;
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
    background: url("../../assets/img/层级.png");
  }

  .link:active {
    background-color: #ececec;
  }

  .accordion li i {
    position: absolute;
    left: 12px;
    top: 50%;
    margin-top: -8px;
    font-size: 16px;
    color: #999999;
    -webkit-transition: all 0.4s ease;
    -o-transition: all 0.4s ease;
    transition: all 0.4s ease;
  }

  .accordion li i.fa-chevron-down {
    font-size: 16px;
  }

  .openImg {
    -webkit-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);
  }

  /**
   * Submenu
   -----------------------------*/
  .submenu {
    overflow: hidden;
    padding: 0 10px;
    opacity: 0;
    max-height: 0px;
    font-size: 14px;
    -webkit-transition: all 0.4s ease;
    -o-transition: all 0.4s ease;
    transition: all 0.4s ease;
  }

  .openChild {
    max-height: 10000vh;
    opacity: 1;
    display: block;
  }

  li {
    list-style-type: none;
    margin-top: 0;
  }

  .accordion .noline::before {
    border-top: 0;
  }

  .slide {
    padding: 0 10px;
    overflow: hidden;
    max-height: 0;
    transition: max-height 0.5s cubic-bezier(0, 1, 0, 1) -0.1s;
  }

  .animate {
    max-height: 9999px;
    transition-timing-function: cubic-bezier(0.5, 0, 1, 0);
    transition-delay: 0s;
  }

  .search-person {}

</style>
<style scoped>
  .vux-no-group-title {
    margin-top: 0 !important;
  }

  .weui-cells {
    margin-top: 0 !important;
  }

  .search-person .weui-cell {
    padding: 15px;
  }

  .search-person .weui-cells:after {
    border-bottom: none;
  }

  .search-person ul li {
    margin-top: 0;
  }

  .vux-label {
    text-overflow: ellipsis !important;
    overflow: hidden !important;
    width: 90% !important;
    display: inline-block !important;
    line-height: 12px !important;
  }

  .vux-cell-primary {
    width: 96% !important;
  }

  .vux-cell-primary p {
    display: inline-block !important;
    width: 100% !important;
  }

</style>
